package com.juyu.miliao.api.service;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.dao.mysql.AppVersionInfoDao;
import com.juyu.miliao.api.dao.mysql.ConfigAppDao;
import com.juyu.miliao.api.dao.mysql.OpenApiStatusDao;
import com.juyu.miliao.api.dao.mysql.VersionHistoryDao;
import com.juyu.miliao.api.domain.AppVersionInfo;
import com.juyu.miliao.api.domain.VersionHistory;
import com.juyu.miliao.api.domain.vo.AppVersionVo;
import com.juyu.miliao.api.domain.vo.ForceVersionVO;
import com.juyu.miliao.api.util.RedisKeys;
import com.juyu.miliao.common.constant.PhoneSystemConstant;
import com.juyu.miliao.common.domain.ConfigApp;
import com.juyu.miliao.common.domain.OpenApiStatus;
import com.juyu.miliao.common.exception.IllegalParamException;
import com.juyu.miliao.common.util.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jh
 * 2018/9/18
 */
@Service
public class VersionHistoryService {

    /**
     * 下载落地页 http://sw.goliaoyou.com/ground/ground001/index.html?id=channel
     */
    private static final String DOWNLOAD_PAGE = "http://sw.qingtiankj4.cn/ground/ground001/index.html?id=";

    private static final String DOWNLOAD_URL_ANDROID = "http://sw.qingtiankj4.cn/apk/huami_";

    private static final String ANDROID_POSTFIX = ".apk";

    private static final String DEFAULT_STRING = "default_";


    @Resource
    private VersionHistoryDao versionHistoryDao;

    @Resource
    private OpenApiService openApiService;

    @Resource
    private ConfigAppDao configAppDao;

    @Resource
    private AppVersionInfoDao appVersionInfoDao;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private OpenApiStatusDao openApiStatusDao;

    /**
     * 版本按.分割
     *
     * @param forceVersion 版本
     * @return List<Integer>
     */
    private static List<Integer> splitVersionString(String forceVersion) {
        List<Integer> list = new ArrayList<>();
        if (!StringUtils.isEmpty(forceVersion)) {
            String[] adrStrings = forceVersion.split("\\.");
            if (adrStrings.length >= 3) {
                list.add(CommonUtil.null2Int(adrStrings[0]));
                list.add(CommonUtil.null2Int(adrStrings[1]));
                list.add(CommonUtil.null2Int(adrStrings[2]));
            }
        }
        return list;
    }

    /**
     * 默认包更新地址=地址+_+appPackageId
     *
     * @param phoneSystem  phoneSystem
     * @param appPackageId appPackageId
     * @return String
     */
    private static String getDownloadUrl(int phoneSystem, String appPackageId, String channel) {
        String url;
        if (phoneSystem == PhoneSystemConstant.ANDROID) {
            url = DOWNLOAD_URL_ANDROID + DEFAULT_STRING + appPackageId + ANDROID_POSTFIX;
        } else if ("huami_appstore".equals(channel)) {
            url = "https://itunes.apple.com/cn/app/id1439419255?mt=8";
        } else {
            url = DOWNLOAD_PAGE + DEFAULT_STRING + appPackageId;
        }
        return url;
    }

    /**
     * 比较是否需要更新
     *
     * @param ids     待比较版本
     * @param version 数据库版本
     * @return boolean　true-需要  false-不需要
     */
    private boolean compare(String[] ids, String version) {
        List<Integer> forceIds = splitVersionString(version);
        int var;
        int forceVar;
        boolean flag = true;
        for (int i = 0; i < 3; i++) {
            var = CommonUtil.null2Int(ids[i]);
            forceVar = forceIds.get(i);
            if (var > forceVar) {
                flag = false;
                break;
            }

            if (var == forceVar) {
                if (i == 2) {
                    flag = false;
                }
                continue;
            }

            //比forceVar小
            break;
        }

        return flag;
    }

    /**
     * 比较版本,并返回最新版本
     * @param ip
     * @param ids         version 以 . 分隔
     * @param phoneSystem 手机系统
     * @return ForceVersionVO
     */
    public ForceVersionVO compareVersion(String ip,String[] ids, int phoneSystem, String channel, String appPackageId, String versionNum) {

        ForceVersionVO vo = new ForceVersionVO();
        //更新地址
//        vo.setUrl(getDownloadUrl(phoneSystem, appPackageId, channel));
        //判断是否审核
        Boolean isAudit = openApiService.getForwardAudit(appPackageId, String.valueOf(phoneSystem), versionNum, channel);
        vo.setIsAudit(isAudit);

        VersionHistory forceVersionHistory = versionHistoryDao.getLastForceUpdatingVersion(phoneSystem, appPackageId);
        if (forceVersionHistory == null) {
            vo.setForceUpdating(false);
            vo.setUrl("");
        } else {
            String forceVersion = forceVersionHistory.getVersion();
            Boolean flag = compare(ids, forceVersion);
            vo.setForceUpdating(flag);
            //更新地址
            vo.setUrl(forceVersionHistory.getUrl());
        }

        VersionHistory newestVersionHistory = versionHistoryDao.getNewestVersion(phoneSystem, appPackageId);
        if (newestVersionHistory == null) {
            vo.setHaveUpdating(false);
        } else {
            boolean flag = compare(ids, newestVersionHistory.getVersion());
            vo.setHaveUpdating(flag);
            String s = newestVersionHistory.getDetail();
            s = s.replaceAll("\\|", "\n");
            vo.setDetail(s);
            vo.setType(phoneSystem);
            vo.setVersion(newestVersionHistory.getVersion());
        }

        OpenApiStatus openApiStatus = openApiStatusDao.getOpenApiStatus(versionNum, phoneSystem, appPackageId, channel);
        if(openApiStatus!=null){
//            if(openApiStatus.getIsUsaIp()==1){
//                String country= QueryIpRegion.queryIP(ip);
//                if("美国".equals(country)){
//                    vo.setIsAudit(true);
//                }
//            }
//            vo.setIsAudit(false);
            String backJsonResource = openApiStatus.getBackJsonResource();
            JSONObject jsStr = JSONObject.parseObject(backJsonResource);
            Object checkSwitch = jsStr.get("checkSwitch");
            if(checkSwitch==null || checkSwitch.equals("")){
                vo.setCheckSwitch(false);
            }else{
                vo.setCheckSwitch(Boolean.parseBoolean(checkSwitch.toString()));
            }
            if(openApiStatus.getIsGameHall()==1){
                vo.setIsGameHall(true);
            }else {
                vo.setIsGameHall(false);
            }
        }else{
            vo.setCheckSwitch(false);
            vo.setIsGameHall(false);

        }
        return vo;
    }

    /**
     * 获取应用更新信息
     * @param userId
     * @param phoneSystem
     * @param appPackageId
     * @param versionNum
     * @return
     */
    public Object getUpdateInfo(long userId, int phoneSystem, String appPackageId, String versionNum) {

        String[] ids = versionNum.split("\\.");
        if (ids.length < 3) {
            throw new IllegalParamException("版本参数错误");
        }

        //根据系统与appPackageId 查看config_app_id
        ConfigApp configApp =configAppDao.getConfigApp(appPackageId,phoneSystem+"");

        int configAppId = configApp.getId().intValue();

        List<AppVersionInfo> list=appVersionInfoDao.getAppVersionInfoByConfigAppId(configAppId);

        if(list.size()>0){
            AppVersionVo appVersionVo = new AppVersionVo();
            AppVersionInfo appVersionInfo = list.get(0);
            boolean flag = compare(ids, appVersionInfo.getVersion());
            //需要更新
            if(flag){

                appVersionVo.setHaveUpdating(flag);

                appVersionVo.setNewVersion(appVersionInfo.getVersion());

                appVersionVo.setUrl(appVersionInfo.getUrl());

                appVersionVo.setDetail(appVersionInfo.getDetail());

                //判断用户是否忽略此版本
                // 1.4.2 安卓前端问题 暂时去掉判断，一直返回需要弹窗
//                String key = RedisKeys.VERSION_IGNORE.getValue(appVersionInfo.getVersion());
//
//                boolean bl = stringRedisTemplate.opsForSet().isMember(key,userId+"");

                appVersionVo.setIgnore(false);

            }else{
                appVersionVo.setHaveUpdating(flag);
            }

            return appVersionVo;

        }else{

            AppVersionVo appVersionVo = new AppVersionVo();

            appVersionVo.setHaveUpdating(false);

            return appVersionVo;
        }

    }

    /**
     * 用户忽略此版本
     * @param userId
     * @param version
     */
    public void getAppIgnoreVersion(long userId, String version) {
        String key = RedisKeys.VERSION_IGNORE.getValue(version);
        stringRedisTemplate.opsForSet().add(key,userId+"");
    }
}
